#include "batchupdatestrategy.h"
#include "statusbarmanager.h"
#include <QDebug>
BatchUpdateStrategy::BatchUpdateStrategy(StatusBarManager* statusBarManager,
                                       int batchIntervalMs,
                                       QObject* parent)
    : QObject(parent)
    , m_statusBarManager(statusBarManager)
    , m_batchTimer(new QTimer(this))
    , m_batchIntervalMs(batchIntervalMs)
    , m_hasPendingUpdates(false)
    , m_pendingState(StatusBarState::idle())
    , m_lastAppliedState(StatusBarState::idle())
{
    // 配置批量更新定时器
    m_batchTimer->setSingleShot(true);
    m_batchTimer->setInterval(m_batchIntervalMs);
    connect(m_batchTimer, &QTimer::timeout, this, &BatchUpdateStrategy::processBatchedUpdates);
}
void BatchUpdateStrategy::applyUpdate(const StatusBarState& newState,
                                    const StatusBarState& oldState,
                                    void* context)
{
    Q_UNUSED(oldState)
    Q_UNUSED(context)
    // 保存最新状态
    m_pendingState = newState;
    m_hasPendingUpdates = true;
    // 启动或重启批量定时器
    m_batchTimer->start();
}
void BatchUpdateStrategy::flushPendingUpdates()
{
    if (m_hasPendingUpdates) {
        m_batchTimer->stop();
        processBatchedUpdates();
    }
}
void BatchUpdateStrategy::reset()
{
    m_batchTimer->stop();
    m_hasPendingUpdates = false;
    m_pendingState = StatusBarState::idle();
    m_lastAppliedState = StatusBarState::idle();
}
void BatchUpdateStrategy::processBatchedUpdates()
{
    if (!m_hasPendingUpdates) {
        return;
    }
    if (!m_statusBarManager) {
        m_hasPendingUpdates = false;
        return;
    }
    StatusBarState currentPending = m_pendingState;
    StatusBarState lastApplied = m_lastAppliedState;
    // Martin Fowler重构：Extract Method - 批量应用所有变化
    // 只更新实际变化的部分
    if (currentPending.fileInfoChanged(lastApplied)) {
        m_statusBarManager->updateStatus(currentPending.fileInfo());
    }
    if (currentPending.pageInfoChanged(lastApplied)) {
        // Martin Fowler重构：只更新总页数，不显示当前页
        m_statusBarManager->updateTotalPages(currentPending.totalPages());
    }
    if (currentPending.cacheInfoChanged(lastApplied)) {
        m_statusBarManager->updateCacheStatus(currentPending.cacheSize(), currentPending.cacheCount());
    }
    if (currentPending.systemStatusChanged(lastApplied)) {
        m_statusBarManager->updateSystemStatus(currentPending.systemStatus());
    }
    // 导出进度变化
    if (currentPending.exportProgressChanged(lastApplied)) {
        // ExportStatusController已经在StatusBarManager中处理导出状态
    }
    // 更新状态
    m_lastAppliedState = currentPending;
    m_hasPendingUpdates = false;
}